package com.harassment.interception.ui.fragments.listManagement;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.harassment.interception.R;
import com.harassment.interception.data.databases.HIDBUtil;
import com.harassment.interception.data.databases.HIDatabase;
import com.harassment.interception.data.databases.entities.BlackList;
import com.harassment.interception.data.databases.entities.WhiteList;
import com.harassment.interception.ui.fragments.dialogFragments.OnNegativeClickListener;
import com.harassment.interception.ui.fragments.dialogFragments.OnPositiveClickListener;
import com.harassment.interception.ui.fragments.listManagement.blackListFragment.BlackListAdapter;
import com.harassment.interception.ui.fragments.listManagement.dialogFragments.AddBlackListDialog;
import com.harassment.interception.ui.fragments.listManagement.dialogFragments.AddWhiteListDialog;
import com.harassment.interception.ui.fragments.listManagement.whiteListFragment.WhiteListAdapter;

import java.util.HashMap;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

public class ListManagementFragment extends Fragment implements View.OnClickListener, OnNegativeClickListener {
    private static final String TAG = "ListManagementFragment";
    private ActionBar mActionBar;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private LMViewPagerAdapter mLMViewPagerAdapter;
    private FloatingActionMenu mFloatingActionMenu;
    private FloatingActionButton mAddWhiteListButton;
    private FloatingActionButton mAddBlackListButton;
    private AddBlackListDialog mAddBlackListDialog;
    private AddWhiteListDialog mAddWhiteListDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mAddBlackListDialog == null) {
            mAddBlackListDialog = new AddBlackListDialog();
            mAddBlackListDialog.setOnNegativeClickListener(this);
            mAddBlackListDialog.setOnPositiveClickListener(new OnPositiveClickListener() {
                @Override
                public void onPositiveClickListener(DialogInterface dialog, int which) {
                    addBlackList();
                }
            });
        }
        if (mAddWhiteListDialog == null) {
            mAddWhiteListDialog = new AddWhiteListDialog();
            mAddWhiteListDialog.setOnNegativeClickListener(this);
            mAddWhiteListDialog.setOnPositiveClickListener(new OnPositiveClickListener() {
                @Override
                public void onPositiveClickListener(DialogInterface dialog, int which) {
                    addWhiteList();
                }
            });
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_management, container, false);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isHidden()) {
            return;
        }
        initActionBar();
        initViewPager();
        initAddActionButton();
    }

    private void initAddActionButton() {
        if (mFloatingActionMenu == null) {
            mFloatingActionMenu = getActivity().findViewById(R.id.add_action_menu);
        }
        if (mAddWhiteListButton == null) {
            mAddWhiteListButton = getActivity().findViewById(R.id.add_white_list);
            mAddWhiteListButton.setOnClickListener(this);
        }
        if (mAddBlackListButton == null) {
            mAddBlackListButton = getActivity().findViewById(R.id.add_black_list);
            mAddBlackListButton.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_white_list:
                mAddWhiteListDialog.show(getFragmentManager(), "addWhiteListDialog");
                break;
            case R.id.add_black_list:
                mAddBlackListDialog.show(getFragmentManager(), "addBlackListDialog");
                break;
        }

        mFloatingActionMenu.close(true);
    }

    private void initViewPager() {
        Log.d(TAG, "initViewPager: 开始");
        Activity activity = getActivity();
        if (activity == null) {
            Log.d(TAG, "initViewPager: 无法获取Activity");
            return;
        }
        if (mViewPager == null) {
            Log.d(TAG, "initViewPager: 初始化viewPager");
            mViewPager = activity.findViewById(R.id.fragment_list_management);
        }
        if (mViewPager.getAdapter() == null) {
            mLMViewPagerAdapter = new LMViewPagerAdapter(activity);
            mViewPager.setAdapter(mLMViewPagerAdapter);
            mTabLayout.setupWithViewPager(mViewPager);
        }
    }

    private void initActionBar() {
        Log.d(TAG, "initActionBar: 开始");
        Activity activity = getActivity();
        if (activity == null) {
            Log.d(TAG, "initActionBar: 无法获取Activity");
            return;
        }
        AppCompatActivity appCompatActivity = null;
        if (activity instanceof AppCompatActivity) {
            appCompatActivity = (AppCompatActivity) activity;
        } else {
            return;
        }

        if (mActionBar == null) {
            Log.d(TAG, "initActionBar: 初始化ActionBar");
            mActionBar = appCompatActivity.getSupportActionBar();
        }

        if (mTabLayout == null) {
            Log.d(TAG, "initActionBar: 初始化TabLayout");
            mTabLayout = (TabLayout) activity.getLayoutInflater().inflate(R.layout.base_tab_layout, null);
        }
        Log.d(TAG, "initActionBar: 配置ActionBar");
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setDisplayShowCustomEnabled(true);
        if (mActionBar.getCustomView() != mTabLayout) {
            Log.d(TAG, "initActionBar: 添加自定义布局");
            mActionBar.setIcon(R.drawable.ic_format_list_bulleted_white_24dp);
            mActionBar.setCustomView(mTabLayout, new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER));
        }
    }

    private void rollbackAction() {
        if (mActionBar == null) {
            return;
        }
        Log.d(TAG, "rollbackAction: 还原ActionBar");
        mActionBar.setDisplayShowTitleEnabled(true);
        mActionBar.setDisplayShowCustomEnabled(false);
        mActionBar.setCustomView(null);
        mActionBar.setIcon(null);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Log.d(TAG, "onHiddenChanged: 开始");
        if (hidden) {
            Log.d(TAG, "onHiddenChanged: 隐藏");
            rollbackAction();
        } else {
            Log.d(TAG, "onHiddenChanged: 显示");
            initActionBar();
            initViewPager();
        }
    }


    @SuppressLint("CheckResult")
    private void addBlackList() {
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                addBlackList();
                emitter.onComplete();
            }
            private void addBlackList(){
                BlackList blackList = new BlackList();
                Dialog dialog = mAddBlackListDialog.getDialog();
                EditText number = dialog.findViewById(R.id.input_number);
                if (number.getText().toString().length() == 0) {
                    return;
                }
                EditText remark = dialog.findViewById(R.id.input_remark);
                RadioButton dark = dialog.findViewById(R.id.radio_dark);
                RadioButton accurate = dialog.findViewById(R.id.radio_accurate);
                CheckBox phone = dialog.findViewById(R.id.not_intercept_phone);
                CheckBox sms = dialog.findViewById(R.id.not_intercept_sms);

                blackList.setNumber(number.getText().toString());
                blackList.setRemark(remark.getText().toString());
                if (dark.isChecked()) {
                    blackList.setModel(HIDatabase.DARK_MODEL);
                } else if (accurate.isChecked()) {
                    blackList.setModel(HIDatabase.ACCURATE_MODEL);
                }
                blackList.setPhone(phone.isChecked());
                blackList.setSms(sms.isChecked());

                HIDBUtil.getBlackListDao().addBlackList(blackList);

                BlackListAdapter adapter = mLMViewPagerAdapter.getBlackListFragment().getBlackListAdapter();
                adapter.getBlackLists().add(0,blackList);
                adapter.setSelectList(new HashMap<Integer, Boolean>());
                adapter.selectInit(adapter.getBlackLists().size(), false);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        mLMViewPagerAdapter.getBlackListFragment().getBlackListAdapter().notifyDataSetChanged();
                        Toast.makeText(getContext(),R.string.add_black_list_success,Toast.LENGTH_SHORT).show();
                    }
                });
    }


    @SuppressLint("CheckResult")
    private void addWhiteList() {
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                addWhiteList();
                emitter.onComplete();
            }
            private void addWhiteList(){
                WhiteList whiteList = new WhiteList();
                Dialog dialog = mAddWhiteListDialog.getDialog();
                EditText number = dialog.findViewById(R.id.input_number);
                if (number.getText().toString().length() == 0) {
                    return;
                }
                EditText remark = dialog.findViewById(R.id.input_remark);
                RadioButton dark = dialog.findViewById(R.id.radio_dark);
                RadioButton accurate = dialog.findViewById(R.id.radio_accurate);
                CheckBox phone = dialog.findViewById(R.id.not_intercept_phone);
                CheckBox sms = dialog.findViewById(R.id.not_intercept_sms);

                whiteList.setNumber(number.getText().toString());
                whiteList.setRemark(remark.getText().toString());
                if (dark.isChecked()) {
                    whiteList.setModel(HIDatabase.DARK_MODEL);
                } else if (accurate.isChecked()) {
                    whiteList.setModel(HIDatabase.ACCURATE_MODEL);
                }
                whiteList.setPhone(phone.isChecked());
                whiteList.setSms(sms.isChecked());
                HIDBUtil.getWhiteListDao().addWhiteList(whiteList);

                WhiteListAdapter whiteListAdapter = mLMViewPagerAdapter.getWhiteListFragment().getWhiteListAdapter();
                whiteListAdapter.getWhiteLists().add(0, whiteList);
                whiteListAdapter.setSelectList(new HashMap<Integer, Boolean>());
                whiteListAdapter.selectInit(whiteListAdapter.getWhiteLists().size(),false);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        mLMViewPagerAdapter.getWhiteListFragment().getWhiteListAdapter().notifyDataSetChanged();
                        Toast.makeText(getContext(),R.string.add_white_list_success,Toast.LENGTH_SHORT).show();
                    }
                });

    }

    @Override
    public void onNegativeClickListener(DialogInterface dialog, int which) {
        dialog.cancel();
    }

}
